package com.mall.controller;
import com.mall.beans.Address;
import com.mall.beans.Dto;
import com.mall.service.AddressService;
import com.mall.util.DtoUtil;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

/**
 * 收货地址表(Address)表控制层
 *
 * @author 蔡文智
 * @since 2020-12-29 09:53:46
 */
@RestController
@RequestMapping("address")
public class AddressController {
    /**
     * 服务对象
     */
    @Resource
    private AddressService addressService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Dto selectOne(Integer id) {
        return DtoUtil.returnOk(addressService.queryById(id));
    }

    @GetMapping("all")
    public Dto all(){return DtoUtil.returnOk(addressService.all());
    }

    @PostMapping("add")
    public Dto add(@RequestBody Address address){
        System.out.println("新增地址");
        Address adr = addressService.test(address.getUserId());
        System.out.println("count:"+adr.getCount());
        if(adr.getCount() > 0){
            adr.setIsDefault(0);
            addressService.updateAdd(adr);
        }
        if (addressService.add(address)>0){
            return DtoUtil.returnOk();
        }else {
            return DtoUtil.returnError(5001,"插入失败");
        }
    }

    @PostMapping("updateAdd")
    public Dto updateAdd(@RequestBody Address address){
        return DtoUtil.returnOk(addressService.updateAdd(address));
    }

    @GetMapping("deleteAdd")
    public Dto deleteAdd(int id){
        int result = addressService.deleteAdd(id);
        if (result > 0){
            return DtoUtil.returnOk(addressService.all());
        }else {
            return DtoUtil.returnError(5002,"删除失败");
        }
    }
}